<script setup>
import { ref } from 'vue'
import { admininfoUpService } from '@/api/admin/admininfo'
import { adminUserStore } from '@/stores'
// 是在使用仓库中数据的初始值 (无需响应式) 解构无问题
const {
  admin: { id, name, phone, address, sex, age },
  getAdmin
} = adminUserStore()
//定义年龄数据验证的函数
const ageRangeRule = (minAge, maxAge) => ({
  validator(rule, value) {
    const age = parseInt(value, 10)
    if ((age !== '' && age < minAge) || age > maxAge) {
      return Promise.reject(`年龄必须在${minAge}岁和${maxAge}岁之间`)
    }
    return Promise.resolve()
  }
})
const Disabled = ref(false)
const formModel = ref({
  id,
  name,
  phone,
  address,
  sex,
  age
})
const clearorder = ref({})

const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: 'blur'
    }
  ],
  age: [ageRangeRule(18, 70)]
}

const proviceDisabled = ref(false)
const cityDisabled = ref(true)
const countryDisabled = ref(true)
const detailAdressDisabled = ref(true)
const addressDetail = ref({})
const baiduPrivice = ref()
const baiduCity = ref()
const baiduCityBelong = ref()
const formRef = ref()
const addresscontainer = ref({
  initprovice: '',
  changedprovice: '',
  initcity: '',
  changedcity: '',
  changedcountry: '',
  initcountry: ''
})

const handleClearValidate = () => {}
const clearAddress = () => {
  formModel.value.address = ''
  addresscontainer.value.initprovice = ''
  addresscontainer.value.changedprovice = ''
  addresscontainer.value.initcity = ''
  addresscontainer.value.changedcity = ''
  addresscontainer.value.changedcountry = ''
  addresscontainer.value.initcountry = ''
  proviceDisabled.value = false
  cityDisabled.value = true
  countryDisabled.value = true
  detailAdressDisabled.value = true
  addressDetail.value = ''
  open()
}

import axios from 'axios'
clearorder.value = formModel.value.address
const open = () => {
  formModel.value.address = clearorder.value
  if (formModel.value.id) {
    addressDetail.value = formModel.value.address.split(' ')
    axios
      .get(
        'api_region_search/v1/?keyword=中国&sub_admin=3&ak=nqSAq8S0isAO5oeDnN6S3amqh9SB2aMP'
      )
      .then(async (response) => {
        baiduPrivice.value = response.data.districts[0].districts
        for (let i = 0; i < baiduPrivice.value.length; i++) {
          if (baiduPrivice.value[i].name == addressDetail.value[0]) {
            addresscontainer.value.initprovice = i
            addresscontainer.value.changedprovice = i
            break
          }
        }
        //拿到省下级的index
        baiduCity.value =
          baiduPrivice.value[addresscontainer.value.initprovice].districts
        for (let i = 0; i < baiduCity.value.length; i++) {
          if (baiduCity.value[i].name === addressDetail.value[1]) {
            addresscontainer.value.initcity = i
            addresscontainer.value.changedcity = i
          }
        } //拿到市下一级
        baiduCityBelong.value =
          baiduCity.value[addresscontainer.value.changedcity].districts
        for (let i = 0; i < baiduCityBelong.value.length; i++) {
          if (baiduCityBelong.value[i].name === addressDetail.value[2]) {
            addresscontainer.value.changedcountry = i
            addresscontainer.value.initcountry = i
          }
        }
      })
      .catch((error) => {
        console.error(error)
      })
  }
}
open()
const submitForm = async () => {
  await formRef.value.validate()
  if (!formModel.value.address) {
    ElMessage({
      message: '请输入完整的地址再提交',
      type: 'warning'
    })
  } else {
    admininfoUpService(formModel.value)
      .then((response) => {
        if (response.data.status === 200) {
          ElMessage.success(`${response.data.message} 请刷新网址`)
          proviceDisabled.value = false
          Disabled.value = ref(true)
          getAdmin()
        } else {
          proviceDisabled.value = true
          dialogVisible.value = fasle
          ElMessage.error(response.data.message)
        }
      })
      .catch((error) => {
        ElMessage.error(error)
      })
    detailAdressDisabled.value = true
  }
}
const handleSelectProviceChange = () => {
  //第一个省级填写直接编写完整地址
  //   if (formModel.value.id) {
  //     formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} `
  //     //剥皮
  baiduCity.value =
    baiduPrivice.value[addresscontainer.value.changedprovice].districts
  //     formModel.value.address = `${formModel.value.address}${baiduCity.value[0].name} `
  //   baiduCityBelong.value =
  //     baiduCity.value[addresscontainer.value.changedcity].districts
  //     formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[0].name} `
  //     formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
  //   }
  proviceDisabled.value = true
  cityDisabled.value = false
  addresscontainer.value.changedcity = ''
  addresscontainer.value.changedcountry = ''
  formModel.value.address = ''
  //addressDetail.value = ''
  //countryDisabled.value = false
}

const handleSelectCityChange = () => {
  //   if (formModel.value.id) {
  //     formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} ` //第一次值
  //     baiduCity.value =
  //       baiduPrivice.value[addresscontainer.value.changedprovice].districts //数据拔一层
  //     formModel.value.address = `${formModel.value.address}${baiduCity.value[addresscontainer.value.changedcity].name} `
  baiduCityBelong.value =
    baiduCity.value[addresscontainer.value.changedcity].districts //传值下去
  //     formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[0].name} `
  //     formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
  //     //console.log(formModel.value.address)
  //   }

  //proviceDisabled.value = false
  cityDisabled.value = true
  countryDisabled.value = false
}
const handleSelectCityBelongChange = () => {
  if (formModel.value.id) {
    formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} ` //第一个
    baiduCity.value =
      baiduPrivice.value[addresscontainer.value.changedprovice].districts //拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCity.value[addresscontainer.value.changedcity].name} `
    baiduCityBelong.value =
      baiduCity.value[addresscontainer.value.changedcity].districts //在拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[addresscontainer.value.changedcountry].name} `
    formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
  }
  //console.log(formModel.value.address)
  countryDisabled.value = true
  detailAdressDisabled.value = false
}
const handleDetailAdressInput = () => {
  if (formModel.value.id) {
    formModel.value.address = `${baiduPrivice.value[addresscontainer.value.changedprovice].name} ` //第一个
    baiduCity.value =
      baiduPrivice.value[addresscontainer.value.changedprovice].districts //拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCity.value[addresscontainer.value.changedcity].name} `
    baiduCityBelong.value =
      baiduCity.value[addresscontainer.value.changedcity].districts //在拔一层数据
    formModel.value.address = `${formModel.value.address}${baiduCityBelong.value[addresscontainer.value.changedcountry].name} `
    formModel.value.address = `${formModel.value.address}${addressDetail.value[3]}`
  }
  detailAdressDisabled.value = true
}
</script>

<template>
  <PageContainer>
    <el-form
      class="el-form1"
      :rules="rules"
      ref="formRef"
      :model="formModel"
      :before-close="handleClearValidate"
    >
      <el-form-item prop="name" label="用户名">
        <el-input
          v-model="formModel.name"
          :prefix-icon="User"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机号">
        <el-input
          v-model="formModel.phone"
          :prefix-icon="Iphone"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label=" 地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址">
        <el-select
          placeholder="省份"
          v-model="addresscontainer.changedprovice"
          @change="handleSelectProviceChange"
          :disabled="proviceDisabled"
        >
          <el-option
            v-for="(item, index) in baiduPrivice"
            :key="index"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
        <el-select
          placeholder="市/区"
          v-model="addresscontainer.changedcity"
          @change="handleSelectCityChange"
          :disabled="cityDisabled"
        >
          <el-option
            v-for="(item, index) in baiduCity"
            :key="index"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
        <el-select
          placeholder="乡镇区县"
          v-model="addresscontainer.changedcountry"
          @change="handleSelectCityBelongChange"
          :disabled="countryDisabled"
        >
          <el-option
            v-for="(item, index) in baiduCityBelong"
            :key="index"
            :label="item.name"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input
          placeholder="请输入详细地址"
          v-model="addressDetail[3]"
          @change="handleDetailAdressInput"
          :disabled="detailAdressDisabled"
          :style="{ width: '450px' }"
        ></el-input>
      </el-form-item>

      <el-form-item label="性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别" prop="sex">
        <el-select
          v-model="formModel.sex"
          style="width: 130px"
          placeholder="请选择"
        >
          <el-option value="男">男</el-option>
          <el-option value="女">女</el-option>
        </el-select>
        <el-form-item
          prop="age"
          style="margin-left: 65px"
          label="年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;龄"
        >
          <el-input
            v-model="formModel.age"
            type="number"
            style="width: 192px"
          ></el-input>
        </el-form-item>
        <el-button
          type="primary"
          style="margin-left: 333px; margin-top: 10px"
          plain
          @click="clearAddress"
          :disabled="Disabled"
          >重置地址信息</el-button
        >
      </el-form-item>

      <el-form-item style="margin-right: 200px">
        <el-button type="primary" @click="submitForm">提交修改</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="NoQuire">取消</el-button>
        <el-button type="primary" @click="sureQuire"> 确定 </el-button>
      </div>
    </template>
  </PageContainer>
</template>
<style>
.el-form1 {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  flex-direction: column;
}
</style>
